package com.jiuwei.threadtest1.service.serviceImpl;

import com.jiuwei.threadtest1.entity.User;
import com.jiuwei.threadtest1.mapper.DownLoadMapper;
import com.jiuwei.threadtest1.service.DownLoadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DownLoadServiceImpl implements DownLoadService {
    @Autowired
    private DownLoadMapper downLoadMapper;
    /**
     * 多线程下载网络图片
     */
    @Override
    public void download() throws InterruptedException {
        //1.创建线程池
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(4, 6,
                30, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100),
                new ThreadPoolExecutor.CallerRunsPolicy());
        //分页查询用户数量，先查询最大id，然后通过给线程分不同的任务。
        int maxId = downLoadMapper.selectCount();
        int pageSize = 100;
        int pages = (int) Math.ceil(maxId * 1.0 / pageSize);
        CountDownLatch latch = new CountDownLatch(pages);   // 关键
        ArrayList<User> users1 = new ArrayList<>();
        for (int i = 0; i < pages; i++) {
            int start = i * pageSize + 1;
            int end = start + pageSize;
            poolExecutor.execute(() -> {
                try {
                    System.out.println("线程：" + Thread.currentThread().getName()+ "开始处理第" + start + "条数据");
                    ArrayList<User> users = downLoadMapper.getUserById(start,end);
                    System.out.println(Thread.currentThread().getName() + "已经处理完第" + end + "条数据" + "users" + users.stream().map(User::getName).collect(Collectors.toList()));
                    synchronized (users1){  //线程安全合并
                        users1.addAll(users);
                        System.out.println("合并完成");
                    }
                    users1.addAll(users);
                } finally {
                    latch.countDown();   //任务完成-1
                }
            });
        }
        latch.await();  //等待所有任务结束
        poolExecutor.shutdown();  //优雅关闭
        System.out.println("线程执行完毕");
        System.out.println("users1" + users1.size());
    }
}
